#include <sys/stat.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
  int fd, flags;
  char temp[] = "/tmp/testXXXXXX";
  setbuf(stdout, NULL);

  fd = mkstemp(temp);
  if (fd == -1)
    printf("Failed to mkstemp\n");
  printf("File offset before fork(); %lld\n",(long long)lseek(fd,0,SEEK_CUR));
  flags = fcntl(fd, F_GETFL);
  if (flags == -1)
    printf("Failed to fcntl get flags F_GETFL\n");
  else
    printf("O_APPEND flag in parent is %s\n",(flags & O_APPEND)?"on":"off");

  switch (fork()) {
  case -1:
    printf("Failed to fork()\n");
  case 0: //child process
    if (lseek(fd, 1000, SEEK_SET) == -1)
      printf("Failed to lseek\n");
    flags = fcntl(fd, F_GETFL);
    if (flags == -1)
      printf("Failed to fcntl get flags\n");
    flags |= O_APPEND;
    if (fcntl(fd, F_SETFL, flags) == -1)
      printf("Failed to fcntl set flags\n");
    _exit(EXIT_SUCCESS);
  default:
    if (wait(NULL) == -1)
      printf("wait ...\n");
    printf("File offset in parent: %lld\n",(long long)lseek(fd,0,SEEK_CUR));
    flags = fcntl(fd,F_GETFL);
    if (flags == -1)
      printf("Failed to fcntl get flags\n");
    printf("O_APPEND flag in parent is %s\n",(flags & O_APPEND)?"on":"off");
    exit(EXIT_SUCCESS);
  }
}

